package users;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Set;

import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;

import networkedmodules.ModuleGroup;

public class UserPermissionEditPanel extends JPanel
{
    private static final long serialVersionUID = 1L;
    private UserGroup group;

    public UserPermissionEditPanel(UserGroup group)
    {
        this.group = group;
        setLayout(new GridLayout(8, group.getSize() + 1));
        add(new JLabel(" "));
        Set<User> users = group.getUsers();
        for (User u : users)
        {
            add(new JLabel(u.getName()));
        }
        int[] types = { UserPermissions.MAY_EDIT_PERMISSIONS,
                UserPermissions.MAY_CHAT, UserPermissions.MAY_ADD_UNITS,
                UserPermissions.MAY_REMOVE_UNITS,
                UserPermissions.MAY_MOVE_UNITS, UserPermissions.MAY_EDIT_UNITS,
                UserPermissions.MAY_EDIT_TERRAIN};
        for(int i = 0; i < types.length; i++)
        {
            add(new JLabel(UserPermissions.names[i]));
            for (User user : users)
            {
                JCheckBox box = new JCheckBox();
                box.setSelected(user.getUserPermissions().getPermission(i));
                box.addActionListener(new PermissionsChangeListener(box, user, i));
                box.setEnabled(group.getSelf().getUserPermissions().getPermission(UserPermissions.MAY_EDIT_PERMISSIONS));
                add(box);
            }
        }
    }
    
    private class PermissionsChangeListener implements ActionListener
    {
        JCheckBox box;
        User user;
        int type;

        public PermissionsChangeListener(JCheckBox box, User user, int type)
        {
            this.box = box;
            this.user = user;
            this.type = type;
        }

        public void actionPerformed(ActionEvent arg0)
        {
            if(type == UserPermissions.MAY_EDIT_PERMISSIONS && box.isSelected())
            {
                user.getUserPermissions().setAllPermissions(true);
            }
            else user.getUserPermissions().setPermissions(type, box.isSelected());
            group.getModuleGroup().sendUpdate(new UserPermissionsUpdate(group.getKey(), group));
            if(group.getModuleGroup().getType() == ModuleGroup.HOST)
                group.makeNotification();
        }
    }
}
